﻿using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace Syngine.Components.Shapes
{
	public abstract class Shape : IDraw
	{
		#region Fields

		private int _drawOrder;
		private bool _visible;

		#endregion

		#region Constructors

		protected Shape(Color color)
		{
			Color = color;
		}

		#endregion

		#region Properties

		protected bool Reload { get; set; }

		protected Color Color { get; set; }

		protected BasicEffect Effect { get; set; }

		/// <summary>
		/// 
		/// </summary>
		public event EventHandler<EventArgs> DrawOrderChanged;

		/// <summary>
		/// 
		/// </summary>
		public event EventHandler<EventArgs> VisibleChanged;

		/// <summary>
		/// 
		/// </summary>
		public int DrawOrder
		{
			get
			{
				return _drawOrder;
			}
			set
			{
				if (_drawOrder != value)
				{
					_drawOrder = value;
					OnDrawOrderChanged();
				}
			}
		}

		/// <summary>
		/// 
		/// </summary>
		public bool Visible
		{
			get
			{
				return _visible;
			}
			set
			{
				if (_visible != value)
				{
					_visible = value;
					OnVisibleChanged();
				}
				_visible = value;
			}
		}

		public VertexPositionColor[] Vertices { get; set; }

		#endregion

		#region Methods

		public bool IsInitialized { get; private set; }

		public virtual void Initialize()
		{
			var graphics = GameContext.Game.GraphicsDevice;

			Effect = new BasicEffect(graphics)
			{
				VertexColorEnabled = true,
				//Projection = GameContext.Camera.Projection
				Projection = Matrix.CreateOrthographicOffCenter(0, graphics.Viewport.Width, graphics.Viewport.Height, 0, 0, 1),
			};

			if (!Reload)
			{
				InitializeCore();
			}
			else
			{
				Reload = false;
			}

			IsInitialized = true;
		}

		public void Update(UpdateContext context)
		{
		}

		public void Draw(DrawContext context)
		{
			Effect.CurrentTechnique.Passes[0].Apply();
			GameContext.Game.GraphicsDevice.DrawUserPrimitives(PrimitiveType.LineStrip, Vertices, 0, Vertices.Length - 1);
		}

		public void LoadContent(LoadContext context)
		{
		}

		public void UnloadContent()
		{
		}

		protected abstract void InitializeCore();

		private void OnVisibleChanged()
		{
			var handler = VisibleChanged;

			if (handler != null)
			{
				handler(this, EventArgs.Empty);
			}
		}

		private void OnDrawOrderChanged()
		{
			var handler = DrawOrderChanged;

			if (handler != null)
			{
				handler(this, EventArgs.Empty);
			}
		}

		#endregion
	}
}
